package com.dd.cloud.user.service.doctor.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.config.obs.PathProperties;
import com.dd.cloud.common.constants.HealthConstants;
import com.dd.cloud.common.constants.IntegralConstants;
import com.dd.cloud.common.constants.UserConstants;
import com.dd.cloud.common.enums.ZkExceptionEnum;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.common.utils.*;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.user.DTO.hosData.AddDoctorImgReq;
import com.dd.cloud.user.DTO.hosData.InsStaffReq;
import com.dd.cloud.user.DTO.hosData.ZekeHosResponse;
import com.dd.cloud.user.config.SuperviseProperties;
import com.dd.cloud.user.entity.admin.AdminSaleInfo;
import com.dd.cloud.user.entity.agent.Agent;
import com.dd.cloud.user.entity.ca.CaDoctor;
import com.dd.cloud.user.entity.doctor.*;
import com.dd.cloud.user.entity.mechan.MechanRank;
import com.dd.cloud.user.mapper.doctor.DoctorDetailApplyMapper;
import com.dd.cloud.user.mapper.doctor.DoctorDetailMapper;
import com.dd.cloud.user.mq.MQConfig;
import com.dd.cloud.user.mq.RabbitSend;
import com.dd.cloud.user.req.consult.ImUpdateUserReq;
import com.dd.cloud.user.req.doctor.*;
import com.dd.cloud.user.res.doctor.*;
import com.dd.cloud.user.service.admin.ISaleInviteDoctorService;
import com.dd.cloud.user.service.agent.IAgentDoctorBindService;
import com.dd.cloud.user.service.ca.ICaDoctorService;
import com.dd.cloud.user.service.consule.ITencentImMsgService;
import com.dd.cloud.user.service.doctor.*;
import com.dd.cloud.user.service.mechan.IMechanRankService;
import com.dd.cloud.user.service.plat.IPlatformLoginService;
import com.dd.cloud.user.vo.DelayMqVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 * 医生详情表 服务实现类
 * </p>
 *
 * @author czg
 * @since 2022-04-27
 */
@Service
@Slf4j
public class DoctorDetailServiceImpl extends ServiceImpl<DoctorDetailMapper, DoctorDetail> implements IDoctorDetailService {
    @Autowired
    private IDoctorUserService doctorUserService;
    @Autowired
    private IMechanRankService mechanRankService;
    @Autowired
    private PathProperties pathProperties;
    @Autowired
    private ISaleInviteDoctorService saleInviteDoctorService;
    @Autowired
    private IAgentDoctorBindService agentDoctorBindService;
    @Autowired
    private IPlatformLoginService platformLoginService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private IDoctorSettingServiceService doctorSettingServiceService;
    @Autowired
    private IDoctorDetailApplyService doctorDetailApplyService;
    @Autowired
    private RabbitSend rabbitSend;
    @Autowired
    private SuperviseProperties superviseProperties;

    @Autowired
    private IBindReviewPresDoctorService bindReviewPresDoctorService;

    @Autowired
    private DoctorDetailApplyMapper doctorDetailApplyMapper;

    @Autowired
    private IDoctorDetailReviewService doctorDetailReviewService;
    @Autowired
    private ICaDoctorService caDoctorService;

    @Autowired
    private IDoctorTaskRecordService doctorTaskRecordService;


    /**
     * 查询医生详细信息
     *
     * @param docId 医生账号ID
     * @return
     */
    @Override
    public DoctorDetailRes queryDoctorDetail(Integer docId) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        if (docId == null) {
            docId = loginInfo.getId();
        }
        DoctorDetailRes res = getBaseMapper().queryDoctorDetail(docId);
        if (res.getIsPresPower() != null && res.getIsPresPower() == 0) {
            res.setReviewPresDoctorCount(bindReviewPresDoctorService.queryBindReviewPresDoctorNormalCount(docId));
        }
        if (StringUtils.isNotBlank(res.getPassword())) {
            res.setPassword("1");
        }
        return res;
    }

    /**
     * 添加医生资料
     *
     * @param req
     */
    @Override
    public void addDoctorDetail(DoctorCreateReq req) {
        DoctorDetail doctorDetail = new DoctorDetail();
        BeanUtils.copyProperties(req, doctorDetail);
        doctorDetail.setAvatar(delPrefix(req.getAvatar()));
        doctorDetail.setStatus(UserConstants.DoctorDetailStatus.NORMAL);
        doctorDetail.setCreateDate(LocalDateTime.now());
        boolean flag = save(doctorDetail);
        if (!flag) {
            throw new ZekeException(ZkExceptionEnum.ADD_ERROR);
        }
    }


    @Autowired
    private ITencentImMsgService tencentImMsgService;

    /**
     * 修改医生资料
     *
     * @param req
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDoctorDetail(DoctorDetailUpdateReq req) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        try {
            req = StringOperUtil.setObjVal(req);
        } catch (IllegalAccessException ignored) {

        }
        DoctorUser du = doctorUserService.getById(req.getDoctorId());
        LambdaQueryWrapper<DoctorDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DoctorDetail::getDoctorId, req.getDoctorId());
        DoctorDetail oldDoctorDetail = this.getOne(queryWrapper);
        if (du == null) {
            throw new ZekeException(ZkExceptionEnum.ACCOUNT_NOT_FOUND);
        }
        if (req.getMechanId() != null && !req.getMechanId().equals(du.getMechanId())) {
            QueryWrapper<MechanRank> qw1 = new QueryWrapper<>();
            qw1.lambda().eq(MechanRank::getId, req.getMechanId());
            MechanRank mechanRank = mechanRankService.getOne(qw1);
            if (mechanRank == null) {
                throw new ZekeException(400, "更改的机构信息不存在");
            }
        }
        if (!req.getMobileNumber().equals(du.getMobileNumber())) {
            QueryWrapper<DoctorUser> qu = new QueryWrapper<>();
            qu.lambda().eq(DoctorUser::getMobileNumber, req.getMobileNumber());
            qu.lambda().notIn(DoctorUser::getStatus, UserConstants.DoctorUserStatus.DEL, UserConstants.DoctorUserStatus.LOGOFF);
            qu.lambda().ne(DoctorUser::getId, du.getId());
            int count = doctorUserService.count(qu);
            if (count > 0) {
                throw new ZekeException(ZkExceptionEnum.PHONE_IS_EXISTS);
            }
        }
        UpdateOldDoctorInfo updateOldDoctorInfo = covertOldData(oldDoctorDetail, du);
        UpdateNewDoctorInfo updateNewDoctorInfo = covertNewData(req);
        //加密
        if (StringUtils.isNotBlank(req.getPassword())) {
            String salt = CodecUtils.generateSalt();
            du.setSalt(salt);
            du.setPassword(CodecUtils.md5Hex(req.getPassword(), du.getSalt()));
        }
        if (StringUtils.isBlank(du.getCodeRecord()) && StringUtils.isNotBlank(req.getCodeRecord())) {
            req.setCodeRecord(req.getCodeRecord().toUpperCase());
            du.setCodeRecord(req.getCodeRecord());
            if (du.getType() == UserConstants.DoctorUserType.PUB) {
                if (req.getCodeRecord().indexOf(HealthConstants.InviteCodePrefixConstants.SALE_PREFIX) != 0) {
                    throw new ZekeException("此邀请码不是销售邀请码");
                } else {
                    AdminSaleInfo adminSaleInfo = saleInviteDoctorService.bindSaleInviteDoctor(req.getCodeRecord(), du.getId());
                    du.setInviteName(adminSaleInfo.getName());
                    du.setInviteType(UserConstants.UserType.AGENT);
                }
            } else if (du.getType().equals(UserConstants.DoctorUserType.PRO)) {
                if (req.getCodeRecord().indexOf(HealthConstants.InviteCodePrefixConstants.DOCTOR_PREFIX) == 0) {
                    QueryWrapper<DoctorUser> qw = new QueryWrapper<>();
                    qw.lambda().eq(DoctorUser::getInviteCode, req.getCodeRecord().toUpperCase());
                    qw.lambda().notIn(DoctorUser::getStatus, UserConstants.DoctorUserStatus.DEL, UserConstants.DoctorUserStatus.LOGOFF);
                    qw.lambda().select(DoctorUser::getId);
                    DoctorUser inviteDoc = doctorUserService.getOne(qw);
                    if (inviteDoc == null) {
                        throw new ZekeException(400, "邀请码不存在,请重新输入");
                    }
                    LambdaQueryWrapper<DoctorDetail> detailLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    detailLambdaQueryWrapper.eq(DoctorDetail::getDoctorId, du.getId());
                    DoctorDetail doctorDetail = this.getOne(detailLambdaQueryWrapper);
                    if (doctorDetail != null) {
                        du.setInviteName(doctorDetail.getName());
                    }
                    du.setInviteDocId(inviteDoc.getId());
                    du.setInviteType(UserConstants.UserType.DOCTOR);
                } else if (req.getCodeRecord().indexOf(HealthConstants.InviteCodePrefixConstants.SALE_PREFIX) == 0) {
                    AdminSaleInfo adminSaleInfo = saleInviteDoctorService.bindSaleInviteDoctor(req.getCodeRecord(), du.getId());
                    du.setInviteName(adminSaleInfo.getName());
                    du.setInviteType(UserConstants.UserType.SALE);
                } else if (req.getCodeRecord().indexOf(HealthConstants.InviteCodePrefixConstants.AGENT_PREFIX) == 0) {
                    Agent agent = agentDoctorBindService.doctorBindAgent(req.getCodeRecord(), du.getId());
                    du.setInviteName(agent.getName());
                    du.setInviteType(UserConstants.UserType.AGENT);
                }
            }
        }
        if (req.getIsCertification() == 1) {
            du.setMobileNumber(req.getMobileNumber()).setMechanId(req.getMechanId());
            du.setIsCertification(UserConstants.IsCertification.certification);
            DoctorDetail doctorDetail = new DoctorDetail();
            BeanUtils.copyProperties(req, doctorDetail);
            doctorDetail.setAvatar(delPrefix(req.getAvatar()));
            doctorDetail.setProvince(StringOperUtil.toNull(req.getProvince()));
            doctorDetail.setCity(StringOperUtil.toNull(req.getCity()));
            doctorDetail.setDistrict(StringOperUtil.toNull(req.getDistrict()));
            doctorDetail.setAddr(StringOperUtil.toNull(req.getAddr()));
            String birthday = DateUtils.extractYearMonthDayOfIdCard(req.getIdCard());
            if (StringUtils.isNotBlank(birthday)) {
                doctorDetail.setBirthDate(LocalDate.parse(birthday));
            } else {
                if (!req.getAge().equals(oldDoctorDetail.getAge())) {
                    doctorDetail.setBirthDate(DateUtils.byAgeNumAndAgeTypeToDate(req.getAge(), 2));
                }
            }
            QueryWrapper<DoctorDetail> qw = new QueryWrapper<>();
            qw.lambda().eq(DoctorDetail::getDoctorId, req.getDoctorId());
            boolean flag = update(doctorDetail, qw);
            if (!flag) {
                throw new ZekeException(ZkExceptionEnum.UPDATE_ERROR);
            }
            if (flag) {
                //修改
                String oldName = oldDoctorDetail.getName();
                String oldAvatar = oldDoctorDetail.getAvatar() == null ? "" : oldDoctorDetail.getAvatar();
                String newAvatar = req.getAvatar() == null ? "" : req.getAvatar();
                String newName = req.getName();
                if (!newName.equals(oldName) || !newAvatar.equals(oldAvatar)) {
                    log.info("姓名字:{},老名字:{},头像:{},{}", newName, oldName, newAvatar, oldAvatar);
                    log.info("编辑医生信息发送im消息----修改医生头像及医生名字");
                    ImUpdateUserReq imUpdateUserReq = new ImUpdateUserReq();
                    imUpdateUserReq.setUserName(newName);
                    imUpdateUserReq.setUserType(1);
                    imUpdateUserReq.setUserId(req.getDoctorId());
                    imUpdateUserReq.setFaceUrl(req.getAvatar());
                    tencentImMsgService.imUpdateImUser(imUpdateUserReq);
                }
            }
            DoctorDetailApplyLastTipRes doctorDetailApplyDetailRes = doctorDetailApplyMapper.getDoctorDetailApplyLastTip(req.getDoctorId(), 1);
            if (doctorDetailApplyDetailRes != null && doctorDetailApplyDetailRes.getStatus() == 3) {
                DoctorDetailApply doctorDetailApply = new DoctorDetailApply();
                BeanUtils.copyProperties(req, doctorDetailApply);
                doctorDetailApply.setDoctorId(req.getDoctorId());
                doctorDetailApply.setStatus(2);
                doctorDetailApply.setType(1);
                doctorDetailApply.setCreateDate(LocalDateTime.now());
                boolean flag3 = doctorDetailApplyService.save(doctorDetailApply);
                if (flag3) {
                    DoctorDetailReview doctorDetailReview = new DoctorDetailReview();
                    doctorDetailReview.setApplyId(doctorDetailApply.getId())
                            .setStatus(2)
                            .setOperName(loginInfo.getName())
                            .setCreateDate(LocalDateTime.now())
                            .setOperId(loginInfo.getId())
                            .setTipCount(doctorDetailApplyDetailRes.getTipCount());
                    boolean fla4 = doctorDetailReviewService.save(doctorDetailReview);
                    if (!fla4) {
                        throw new ZekeException("保存失败");
                    }
                } else {
                    throw new ZekeException("保存失败");
                }
            }
        } else if (req.getIsCertification() == 0) {
            //查看是否有编辑
            String json = com.dd.cloud.common.utils.BeanUtils.getChangedFields(updateNewDoctorInfo, updateOldDoctorInfo);
            if (StringUtils.isNotBlank(json) && !"{}".equals(json)) {
                String oldData = JSON.toJSONString(updateOldDoctorInfo);
                DoctorDetailApply doctorDetailApply = new DoctorDetailApply();
                BeanUtils.copyProperties(req, doctorDetailApply);
                doctorDetailApply.setType(5).setStatus(1).setCreateDate(LocalDateTime.now()).setOldData(oldData).setNewData(json);
                String birthday = DateUtils.extractYearMonthDayOfIdCard(req.getIdCard());
                if (StringUtils.isNotBlank(birthday)) {
                    doctorDetailApply.setBirthDate(LocalDate.parse(birthday));
                } else {
                    if (!req.getAge().equals(oldDoctorDetail.getAge())) {
                        doctorDetailApply.setBirthDate(DateUtils.byAgeNumAndAgeTypeToDate(req.getAge(), 2));
                    }
                }
                doctorDetailApplyService.save(doctorDetailApply);
            }
        }
        du.setRemark(req.getRemark());
        doctorUserService.updateById(du);
    }

    private UpdateNewDoctorInfo covertNewData(DoctorDetailUpdateReq req) {
        UpdateNewDoctorInfo newDoctorInfo = new UpdateNewDoctorInfo();
        newDoctorInfo.setIdCard(req.getIdCard()).setName(req.getName()).setSex(req.getSex()).setBirthDate(req.getBirthDate()).setAge(req.getAge()).setProvince(req.getProvince()).setCity(req.getCity()).setDistrict(req.getDistrict()).setAddr(req.getAddr()).setIntroduction(req.getIntroduction()).setMobileNumber(req.getMobileNumber()).setGoodAt(req.getGoodAt()).setProCertificate(req.getProCertificate()).setMechanId(req.getMechanId()).setOrganization(req.getOrganization()).setQualificationType(req.getQualificationType()).setQuaCertificateNo(req.getQuaCertificateNo()).setQuaCertificatePhoto(req.getQuaCertificatePhoto()).setQuaCertificateDate(req.getQuaCertificateDate()).setPraCertificateNo(req.getPraCertificateNo()).setPraCertificatePhoto(req.getPraCertificatePhoto()).setProCertificatePhoto(req.getProCertificatePhoto()).setHealthCommitteePhoto(req.getHealthCommitteePhoto()).setAvatar(req.getAvatar()).setCertificateType(req.getCertificateType()).setCertificateName(req.getCertificateName()).setCertificateUrl(req.getCertificateUrl()).setPraCertificateDate(req.getPraCertificateDate()).setWorkCard(req.getWorkCard()).setAttribute(req.getAttribute()).setDoctorType(req.getDoctorType()).setTechnicalCategories(req.getTechnicalCategories()).setProfessionalTechnicians(req.getProfessionalTechnicians()).setPracticeArea(req.getPracticeArea()).setWorkDate(req.getWorkDate());
        return newDoctorInfo;
    }

    private UpdateOldDoctorInfo covertOldData(DoctorDetail doctorDetail, DoctorUser du) {
        UpdateOldDoctorInfo oldDoctorInfo = new UpdateOldDoctorInfo();
        oldDoctorInfo.setIdCard(doctorDetail.getIdCard()).setName(doctorDetail.getName()).setSex(doctorDetail.getSex()).setBirthDate(doctorDetail.getBirthDate()).setAge(doctorDetail.getAge()).setProvince(doctorDetail.getProvince()).setCity(doctorDetail.getCity()).setDistrict(doctorDetail.getDistrict()).setAddr(doctorDetail.getAddr()).setIntroduction(doctorDetail.getIntroduction()).setMobileNumber(doctorDetail.getMobileNumber()).setGoodAt(doctorDetail.getGoodAt()).setProCertificate(doctorDetail.getProCertificate()).setMechanId(du.getMechanId()).setOrganization(doctorDetail.getOrganization()).setQualificationType(doctorDetail.getQualificationType()).setQuaCertificateNo(doctorDetail.getQuaCertificateNo()).setQuaCertificatePhoto(doctorDetail.getQuaCertificatePhoto()).setQuaCertificateDate(doctorDetail.getQuaCertificateDate()).setPraCertificateNo(doctorDetail.getPraCertificateNo()).setPraCertificatePhoto(doctorDetail.getPraCertificatePhoto()).setProCertificatePhoto(doctorDetail.getProCertificatePhoto()).setHealthCommitteePhoto(doctorDetail.getHealthCommitteePhoto()).setAvatar(doctorDetail.getAvatar()).setCertificateType(doctorDetail.getCertificateType()).setCertificateName(doctorDetail.getCertificateName()).setCertificateUrl(doctorDetail.getCertificateUrl()).setPraCertificateDate(doctorDetail.getPraCertificateDate()).setWorkCard(doctorDetail.getWorkCard()).setAttribute(doctorDetail.getAttribute()).setDoctorType(doctorDetail.getDoctorType()).setTechnicalCategories(doctorDetail.getTechnicalCategories()).setProfessionalTechnicians(doctorDetail.getProfessionalTechnicians()).setPracticeArea(doctorDetail.getPracticeArea()).setWorkDate(doctorDetail.getWorkDate());
        return oldDoctorInfo;
    }

    /**
     * 修改医生资料 内部service调用
     *
     * @param dd
     */
    @Override
    public void updateDoctorDetail(DoctorDetail dd) {
        QueryWrapper<DoctorDetail> qw = new QueryWrapper<>();
        qw.lambda().eq(DoctorDetail::getDoctorId, dd.getDoctorId());
        update(dd, qw);
    }

    /**
     * 修改医生资料 自定义参数
     *
     * @param req
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDoctorDetailUpdateOpt(DoctorDetailUpdateOptReq req) {
        if (req.getDoctorId() == null) {
            LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
            req.setDoctorId(loginInfo.getId());
        }
        QueryWrapper<DoctorDetail> qw = new QueryWrapper<>();
        qw.lambda().eq(DoctorDetail::getDoctorId, req.getDoctorId());
        qw.lambda().eq(DoctorDetail::getStatus, UserConstants.DoctorDetailStatus.NORMAL);
        qw.lambda().select(DoctorDetail::getId, DoctorDetail::getName, DoctorDetail::getAvatar, DoctorDetail::getIntroduction);
        DoctorDetail dd = getOne(qw);
        String doctorName = dd.getName();
        if (dd == null) {
            throw new ZekeException(400, "医生资料不存在");
        }
        String oldAvatar = dd.getAvatar() == null ? "" : dd.getAvatar();
        String newAvatar = req.getAvatar() == null ? "" : req.getAvatar();
        String oldIntroduction = dd.getIntroduction() == null ? "" : dd.getIntroduction();
        BeanUtils.copyProperties(req, dd);
        boolean flag = updateById(dd);
        if (!flag) {
            throw new ZekeException(ZkExceptionEnum.UPDATE_ERROR);
        }
        if (!newAvatar.equals(oldAvatar)) {
            log.info("头像:{},{},名字:{}", newAvatar, oldAvatar, doctorName);
            log.info("====医生端编辑头像,发送im消息======");
            ImUpdateUserReq imUpdateUserReq = new ImUpdateUserReq();
            imUpdateUserReq.setUserName(doctorName);
            imUpdateUserReq.setUserType(1);
            imUpdateUserReq.setUserId(req.getDoctorId());
            imUpdateUserReq.setFaceUrl(req.getAvatar());
            tencentImMsgService.imUpdateImUser(imUpdateUserReq);
        }
        //发送积分
        if (StringUtils.isBlank(oldAvatar) && StringUtils.isNotBlank(newAvatar)) {
            String params = IntegralConstants.IntegralType.SEVENTEEN_TYPE + "-" + dd.getDoctorId();
            log.info("上传个人头像获取积分,参数:{}", params);
            rabbitSend.sendMessage(MQConfig.INTEGRAL_EXCHANGE, MQConfig.INTEGRAL_QUEUE, params);
            saveTaskRecord(dd.getDoctorId(),IntegralConstants.IntegralType.SEVENTEEN_TYPE);
        }
        if (StringUtils.isBlank(oldIntroduction) && StringUtils.isNotBlank(req.getIntroduction())) {
            String params = IntegralConstants.IntegralType.THREE_TYPE + "-" + dd.getDoctorId();
            log.info("上传个人简历获取积分,参数:{}", params);
            rabbitSend.sendMessage(MQConfig.INTEGRAL_EXCHANGE, MQConfig.INTEGRAL_QUEUE, params);
            saveTaskRecord(dd.getDoctorId(),IntegralConstants.IntegralType.THREE_TYPE);
        }
    }

    public void saveTaskRecord(Integer doctorId,Integer type){
        DoctorTaskRecord doctorTaskRecord = new DoctorTaskRecord();
        doctorTaskRecord.setDoctorId(doctorId)
                .setIsShow(1)
                .setStatus(1)
                .setType(type)
                .setCreateDate(LocalDateTime.now());
        doctorTaskRecordService.save(doctorTaskRecord);
        DelayMqVo<Integer> delayMqVo = new DelayMqVo<>();
        delayMqVo.setT(doctorTaskRecord.getId());
        delayMqVo.setType(DelayMqVo.DelayMqVoType.DOCTOR_TASK);
        //毫秒级 当前时间距离24点时间差
        long ms = DateUtils.nowUtilEndDate();
        rabbitSend.sendMessageDelay(MQConfig.DELAY_EXCHANGE, MQConfig.DELAY_KEY, delayMqVo, ms);
    }

    /**
     * 注册医生账号 生成初始资料
     *
     * @param req
     */
    @Override
    public void registryDoctorUser(DoctorRegistryReq req) {
        DoctorDetail dd = new DoctorDetail();
        dd.setName(req.getName());
        dd.setMobileNumber(req.getPhone());
        dd.setDoctorId(req.getDoctorId());
        dd.setStatus(UserConstants.DoctorDetailStatus.NORMAL);
        dd.setCreateDate(LocalDateTime.now());
        if (StringUtils.isBlank(req.getName())) {
            dd.setName(req.getPhone());
        }
        boolean flag = save(dd);
        if (!flag) {
            throw new ZekeException(ZkExceptionEnum.ADD_ERROR);
        }
    }

    /**
     * 查询医生id以及名称 下拉列表专用
     *
     * @param keyword
     * @return
     */
    @Override
    public List<DoctorUserSelectRes> queryDoctorUserSelect(String keyword) {
        return getBaseMapper().queryDoctorUserSelect(keyword);
    }

    /**
     * 删除医生详情
     *
     * @param docId
     */
    @Override
    public void delDoctorDetail(Integer docId) {
        UpdateWrapper<DoctorDetail> uw = new UpdateWrapper<>();
        uw.lambda().eq(DoctorDetail::getDoctorId, docId);
        uw.lambda().set(DoctorDetail::getStatus, UserConstants.DoctorDetailStatus.DEL);
        update(uw);
    }

    //TODO 待完善
    @Override
    public IPage<InternetDoctorRes> queryDoctorPage(InternetDoctorReq req) {
        IPage<InternetDoctorRes> page = req.pagePojo();
        IPage<InternetDoctorRes> res = this.getBaseMapper().queryDoctorPage(page, req);
        //判断是否可以推送
        if (req.getType() == 1) {
            checkIsPush(res);
        }
        return res;
    }

    private void checkIsPush(IPage<InternetDoctorRes> res) {
        if (res != null && CollectionUtil.isNotEmpty(res.getRecords())) {
            for (InternetDoctorRes internetDoctorRes : res.getRecords()) {
                internetDoctorRes.setIsPush(getIsPush(internetDoctorRes.getDoctorId()));
            }
        }
    }

    public Integer getIsPush(Integer doctorId) {
        DoctorDetailRes doctorDetail = this.queryDoctorDetail(doctorId);
        if (doctorDetail != null) {
            String avatar = doctorDetail.getAvatar();
            String docotorName = doctorDetail.getName();
            Integer age = doctorDetail.getAge();
            String province = doctorDetail.getProvince();
            String city = doctorDetail.getCity();
            String district = doctorDetail.getDistrict();
            String organization = doctorDetail.getOrganization();
            String mechanName = doctorDetail.getMechanName();
            String goodAt = doctorDetail.getGoodAt();
            String idCard = doctorDetail.getIdCard();
            String mobileNumber = doctorDetail.getMobileNumber();
            if (StringUtils.isBlank(docotorName) || age == null || StringUtils.isBlank(province) || StringUtils.isBlank(city) || StringUtils.isBlank(district) || StringUtils.isBlank(organization) || StringUtils.isBlank(mechanName) || StringUtils.isBlank(goodAt) || StringUtils.isBlank(idCard) || StringUtils.isBlank(mobileNumber) || StringUtils.isBlank(avatar)) {
                return 0;
            }
            Integer qualificationType = doctorDetail.getQualificationType();
            if (qualificationType == 1) {
                if (doctorDetail.getCertificateType() == null || StringUtils.isBlank(doctorDetail.getQuaCertificateNo()) || doctorDetail.getQuaCertificateDate() == null || StringUtils.isBlank(doctorDetail.getCertificateUrl())) {
                    return 0;

                }
            }
            if (qualificationType == 2) {
                if (StringUtils.isBlank(doctorDetail.getQuaCertificateNo()) || doctorDetail.getQuaCertificateDate() == null || StringUtils.isBlank(doctorDetail.getPraCertificateNo()) || doctorDetail.getPraCertificateDate() == null || StringUtils.isBlank(doctorDetail.getPraCertificatePhoto())) {
                    return 0;
                }
            }
            if (StringUtils.isBlank(doctorDetail.getWorkCard()) || StringUtils.isBlank(doctorDetail.getAttribute()) || StringUtils.isBlank(doctorDetail.getDoctorType()) || StringUtils.isBlank(doctorDetail.getProfessionalTechnicians()) || StringUtils.isBlank(doctorDetail.getTechnicalCategories()) || StringUtils.isBlank(doctorDetail.getPracticeArea()) || doctorDetail.getWorkDate() == null) {
                return 0;
            } else {
                return 1;
            }
        }
        return 0;
    }

    @Override
    public String getDoctorQr(String page, String param, Integer doctorId) {
        log.info("页面路径:{},参数:{}", page, param);
        DoctorUser doctorUser = doctorUserService.getById(doctorId);
        if (doctorUser.getIsCertification() == 0) {
            throw new ZekeException("医生暂未认证");
        }
        LambdaQueryWrapper<DoctorSettingService> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DoctorSettingService::getDoctorId, doctorId).last("limit 1");
        DoctorSettingService doctorSettingService = doctorSettingServiceService.getOne(wrapper);
        if (doctorSettingService == null) {
            throw new ZekeException("医生暂未设置业务,请先业务设置");
        }
        param = "doctorId=" + doctorId;
        String key = platformLoginService.getWxQr("pages/imageTextDoctorDetail/imageTextDoctorDetail", param);
        return key;
    }

    /**
     * 获取患者公众号二维码
     *
     * @return
     */
    @Override
    public String getPatientGZHWxQr(Integer docId, String param) {
        return platformLoginService.getPatientGZHWxQr(docId, param);
    }

    @Override
    public void pushInternetDoctor(List<Integer> doctorIds) {
        throw new ZekeException("暂未开放此功能");
    }

    @Override
    public IPage<InternetDoctorApplyRes> queryInternetDoctorPage(DoctorInternetApplyReq req) {
        if (StringUtils.isBlank(req.getStatusStr())) {
            req.setStatusStr("1,2,3");
        }
        IPage<InternetDoctorApplyRes> page = req.pagePojo();
        IPage<InternetDoctorApplyRes> res = this.getBaseMapper().queryInternetDoctorPage(page, req);
        return res;
    }

    /***
     * 获取机构名
     */
    @Override
    public String getDoctorMechanName(Integer doctorId) {
        LambdaQueryWrapper<DoctorUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DoctorUser::getId, doctorId).select(DoctorUser::getMechanId);
        DoctorUser doctorUser = doctorUserService.getOne(wrapper);
        LambdaQueryWrapper<MechanRank> qw = new LambdaQueryWrapper<>();
        qw.eq(MechanRank::getId, doctorUser.getMechanId());
        MechanRank mechanRank = mechanRankService.getOne(qw);
        if (mechanRank != null) {
            return mechanRank.getName();
        }
        return "广州阿康中医诊所有限公司";
    }

    @Override
    public String getDoctorName(Integer doctorId) {
        LambdaQueryWrapper<DoctorDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DoctorDetail::getDoctorId, doctorId).select(DoctorDetail::getName);
        DoctorDetail doctorDetail = this.getOne(wrapper);
        return doctorDetail.getName();
    }

    @Override
    public List<DoctorIntegraRes> queryIntegralList(DoctorIntegralReq doctorIntegralReq) {
        if (doctorIntegralReq.getStatus() == null) {
            doctorIntegralReq.setStatus("-2,2,3");
        }


        return null;
    }

    /**
     * @param :
     * @return List<DoctorDetail>
     * @description 查询需要上传到监管平台的医生数据
     * @author czg
     * @date 2024/3/4 14:30
     */
    @Override
    public List<DoctorDetail> getSuperviseDoctorList() {
        List<DoctorDetail> list = getBaseMapper().getSuperviseDoctorList();
        return list;
    }

    /**
     * @param :
     * @return void
     * @description 发送医生数据到监管平台
     * @author czg
     * @date 2023/10/23 16:18
     */
    @Override
    public void sendDocDataToSupervise() {
        String staff = superviseProperties.getStaff();
        QueryWrapper<DoctorDetail> qw = new QueryWrapper<>();
        //TODO 查询需要上传到监管平台的医生数据...

        LocalDateTime time = LocalDateTime.now();
        String format = time.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));

        List<DoctorDetail> list = getSuperviseDoctorList();
        list.forEach(item -> {
            //医生头像地址
            String headImg = "";
            if (StringUtils.isNotBlank(item.getAvatar())) {
                AddDoctorImgReq imgReq = new AddDoctorImgReq();
                imgReq.setType(1);
                imgReq.setFolder(PinYinUtils.chineseToPinyinSell(item.getName()) + item.getDoctorId());
                imgReq.setImgUrl(item.getAvatar());
                imgReq.setTimeStamp(format);
                imgReq.setSign(ObjectUtils.pinyinSort(imgReq));
                imgReq.setSign(DigestUtils.md5Hex(imgReq.getSign()));
                HttpHeaders head = new HttpHeaders();
                head.setContentType(MediaType.APPLICATION_JSON_UTF8);
                HttpEntity<String> entity = new HttpEntity<>(JsonUtils.objectToStr(imgReq), head);
                String result = restTemplate.postForObject(superviseProperties.getUploadimg(), entity, String.class);
                //String result = restTemplate.getForObject(superviseProperties.getUploadimg(), String.class);
                log.debug("上传监管平台 医生图片返回:{}", result);
                ZekeHosResponse<String> zekeHosResponse = JsonUtils.strToObject(result, ZekeHosResponse.class);
                if (zekeHosResponse.getCode() == 2000) {
                    headImg = zekeHosResponse.getBody();
                }
            }
            //医生资格证地址
            String quaCertificatePhoto = "";
            if (StringUtils.isNotBlank(item.getQuaCertificatePhoto())) {
                AddDoctorImgReq imgReq = new AddDoctorImgReq();
                imgReq.setType(1);
                imgReq.setFolder(PinYinUtils.chineseToPinyinSell(item.getName()) + item.getDoctorId());
                imgReq.setImgUrl(item.getQuaCertificatePhoto());
                imgReq.setTimeStamp(format);
                imgReq.setSign(ObjectUtils.pinyinSort(imgReq));
                imgReq.setSign(DigestUtils.md5Hex(imgReq.getSign()));
                HttpHeaders head = new HttpHeaders();
                head.setContentType(MediaType.APPLICATION_JSON_UTF8);
                HttpEntity<String> entity = new HttpEntity<>(JsonUtils.objectToStr(imgReq), head);
                String result = restTemplate.postForObject(superviseProperties.getUploadimg(), entity, String.class);
                //String result = restTemplate.getForObject(superviseProperties.getUploadimg(), String.class);
                log.debug("上传监管平台 医生资格图片返回:{}", result);
                ZekeHosResponse<String> zekeHosResponse = JsonUtils.strToObject(result, ZekeHosResponse.class);
                if (zekeHosResponse.getCode() == 2000) {
                    quaCertificatePhoto = zekeHosResponse.getBody();
                }
            }
            //医生执业证地址
            String praCertificatePhoto = "";
            if (StringUtils.isNotBlank(item.getPraCertificatePhoto())) {
                AddDoctorImgReq imgReq = new AddDoctorImgReq();
                imgReq.setType(1);
                imgReq.setFolder(PinYinUtils.chineseToPinyinSell(item.getName()) + item.getDoctorId());
                imgReq.setImgUrl(item.getPraCertificatePhoto());
                imgReq.setTimeStamp(format);
                imgReq.setSign(ObjectUtils.pinyinSort(imgReq));
                imgReq.setSign(DigestUtils.md5Hex(imgReq.getSign()));
                HttpHeaders head = new HttpHeaders();
                head.setContentType(MediaType.APPLICATION_JSON_UTF8);
                HttpEntity<String> entity = new HttpEntity<>(JsonUtils.objectToStr(imgReq), head);
                String result = restTemplate.postForObject(superviseProperties.getUploadimg(), entity, String.class);
                //String result = restTemplate.getForObject(superviseProperties.getUploadimg(), String.class);
                log.debug("上传监管平台 医生执业图片返回:{}", result);
                ZekeHosResponse<String> zekeHosResponse = JsonUtils.strToObject(result, ZekeHosResponse.class);
                if (zekeHosResponse.getCode() == 2000) {
                    praCertificatePhoto = zekeHosResponse.getBody();
                }
            }
            InsStaffReq req = new InsStaffReq();
            req.setJgdm("0Y41940F29AXTM1114");
            req.setYhrygh(String.valueOf(item.getDoctorId()));
            req.setYhryxm(item.getName());
            req.setXb(item.getSex());
            req.setCsrq(item.getBirthDate());
            req.setSfzh(item.getIdCard());
            req.setZjlbdm("01");
            req.setKsdm("1");
            req.setZyjszwdm("231");
            req.setZyjszwlbdm("3");
            req.setZzlbmc("资格证");
            req.setZgzsbh(item.getQuaCertificateNo());
            req.setZghdsj(item.getQuaCertificateDate());
            req.setZyzsbm(item.getPraCertificateNo());
            req.setFzrq(item.getPraCertificateDate());
            req.setZydd("阿康中医诊所");
            req.setZyfw("50");
            req.setZyzyyljgdm("91440101MA9Y4TX21F");
            req.setZyzyyymc("阿康中医诊所");
            req.setQkysbz("F");
            req.setSjhm(item.getMobileNumber());
            req.setCjgzrq(item.getWorkDate());
            req.setZcsj(LocalDate.now());
            req.setGrzpcfdz(headImg);
            req.setZgzcfdz(quaCertificatePhoto);
            req.setZyzcfdz(praCertificatePhoto);
            req.setSjscsj(item.getCreateDate());
            req.setCxbz("1");
            req.setTimeStamp(format);
            req.setSign(ObjectUtils.pinyinSort(req));
            req.setSign(DigestUtils.md5Hex(req.getSign()));

            HttpHeaders head = new HttpHeaders();
            head.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> entity = new HttpEntity<>(JsonUtils.objectToStr(req), head);
            String result = restTemplate.postForObject(staff, entity, String.class);
            log.debug("上传监管平台 医生信息上传返回:{}", result);
            ZekeHosResponse<String> zekeHosResponse = JsonUtils.strToObject(result, ZekeHosResponse.class);
            if (zekeHosResponse.getCode() != 2000) {
                //TODO 上传失败
                log.error("上传医生数据到监管平台失败:{}", zekeHosResponse.getMessage());
            } else {
                UpdateWrapper<CaDoctor> updateWrapper = new UpdateWrapper<>();
                updateWrapper.lambda().eq(CaDoctor::getAccount, item.getMobileNumber())
                        .eq(CaDoctor::getStatus, 2)
                        .set(CaDoctor::getStatus, 1);
                caDoctorService.update(updateWrapper);
            }
        });
    }

    /**
     * @param doctorId: 医生id
     * @return DoctorConsultDetailRes
     * @description 医生咨询问诊的详情
     * @author czg
     * @date 2023/7/10 15:36
     */
    @Override
    public DoctorConsultDetailRes consultDoctorDetail(Integer doctorId) {

        return getBaseMapper().consultDoctorDetail(doctorId);
    }

    public String delPrefix(String str) {
        if (str == null) {
            return "";
        }
        str = str.replace(pathProperties.getImageServer(), "");
        return str;
    }


}
